<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      ref="crud"
      :search.sync="query"
      :before-open="beforeOpen"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出 </el-button>
      </template>
      <template slot="sequenceDefinitionSubTypeSearch">
        <el-select v-model="query.sequenceDefinitionSubType" placeholder="请选择业务小类" :clearable="true">
          <el-option v-for="cateItem in subTypeList" :key="cateItem.value" :label="cateItem.label" :value="cateItem.value"> </el-option>
        </el-select>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="{ row }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" @click="rowView(row)">详情</el-button>
        <el-button icon="el-icon-printer" size="small" type="text" @click="rowPrint(row)" :disabled="!isShowBtn(row)">
          <span v-if="row.isPrinted === 0 && !row.packLevelType">打印</span>
          <span v-if="row.isPrinted === 1">重打</span>
        </el-button>
        <el-button size="small" type="text" @click="handleRevoke(row)" :disabled="!isShowRevokeBtn(row)">撤销</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" @click="rowScrap(row)" :disabled="!isShowScrapBtn(row)">报废</el-button>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <el-dialog append-to-body :title="title" v-if="printInfoModel" :visible.sync="printInfoModel" width="35%">
      <div v-if="title === '重打'" style="display: flex; justify-content: center; margin-bottom: 10px">
        <span style="color: red">注：仅需修改流水号即可，重打的起始流水号和结束流水号需在原流水号范围内</span>
      </div>
      <avue-form ref="printForm" v-model="printInfo" :option="printInfoOption"> </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="printSubmit" :loading="btnLoading"
          ><i class="el-icon-printer"></i><span>{{ title }}</span></el-button
        >
        <el-button size="small" @click="printInfoModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <!--撤销-->
    <el-dialog append-to-body title="撤销" :visible.sync="revokeVisible" width="30%" @close="closeRevokeDialog">
      <avue-form ref="revokeForm" v-model="revoke" :option="revokeOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="revokeSubmit"><span>撤 销</span></el-button>
        <el-button size="small" @click="revokeVisible = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <el-dialog append-to-body title="报废" :visible.sync="scrapModel" width="30%" @close="closeScrapModel">
      <div style="margin-left: 30px">
        <span style="color: red">注：作废的起始流水号和结束流水号需在原流水号范围内</span>
      </div>
      <avue-form ref="scrapForm" v-model="scrap" :option="scrapOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="scrapSubmit"><i class="el-icon-delete"></i><span>作 废</span></el-button>
        <el-button size="small" @click="scrapModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <el-dialog append-to-body @close="closeDetailModel" v-if="detailModal" class="detail" :visible.sync="detailModal" title="详情" width="60%" top="5vh">
      <div class="sail-header-dialog-content">
        <avue-crud
          ref="crud"
          :table-loading="detailLoading"
          :data="detailData"
          :option="detailOption"
          :page.sync="detailPage"
          @current-change="currentDetailChange"
          @size-change="sizeDetailChange"
        >
        </avue-crud>
      </div>
    </el-dialog>
    <print-time-input-form :visible.sync="printDialog" :other-info-option="otherInfoOption" @printInfo="(otherInfo) => handlePrintSequence(otherInfo)"></print-time-input-form>
    <!-- 生成条码     -->
    <el-dialog append-to-body :title="dialogTitle" :visible.sync="barcodeDialog" width="50%">
      <div class="sail-header-dialog-content">
        <avue-crud
          ref="bigCrud"
          :option="bigPackOption"
          :data="bigPackData"
          :table-loading="bigLoading"
          :page.sync="bigPage"
          v-model="bigForm"
          @selection-change="bigSelectionChange"
          @size-change="bigSizeChange"
          @current-change="bigCurrentChange"
        >
          <template slot="level">
            <span>大包</span>
          </template>
          <template slot="menuLeft">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-delete"
              plain
              v-if="dialogTitle === '重打'"
              @click="handleMultiBigPackReprint"
              :disabled="!bigSelectionList.length"
              >重 打
            </el-button>
          </template>
          <template slot-scope="{ row }" slot="menu">
            <el-button type="text" size="small" @click="handleViewSmallPack(row)">小包详情</el-button>
            <el-button type="text" size="small" v-if="dialogTitle === '重打'" @click="handleReprint(row)" :disabled="row.status === 1">重打 </el-button>
          </template>
        </avue-crud>
      </div>
    </el-dialog>

    <el-dialog append-to-body title="小包详情" :visible.sync="smallDialog" width="50%">
      <div class="sail-header-dialog-content">
        <avue-crud
          ref="smallCrud"
          :option="smallPackOption"
          :data="smallPackData"
          :table-loading="smallLoading"
          :page.sync="smallPage"
          v-model="smallForm"
          @selection-change="detailSelectionChange"
          @size-change="detailSizeChange"
          @current-change="detailCurrentChange"
        >
          <template slot="level">
            <span>小包</span>
          </template>

          <template slot="menuLeft">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-delete"
              plain
              v-if="dialogTitle === '重打'"
              @click="handleMultiSmallPackReprint"
              :disabled="!detailSelection.length"
              >重 打
            </el-button>
          </template>
          <template slot-scope="{ row }" slot="menu">
            <el-button type="text" size="small" v-if="dialogTitle === '重打'" @click="handleReprint(row)">重打 </el-button>
          </template>
        </avue-crud>
      </div>
    </el-dialog>
  </basic-container>
</template>
<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import CommonPrintersTemplate from '@/components/common-printers-template/common-printers-template.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import { getPage, productSnPrint, productSnRePrint, malfunctionSnPrint, malfunctionSnRePrint } from '@/api/labelManagement/labelRecord';
import { getSeqNoRules, subTypeMap } from '@/util/global';
import { getCategory } from '@/api/warehouse/materialRules';
import {
  getPrinterNew,
  warehouseScrap,
  warehousePrint,
  finishSnPrint,
  warehouseSnPrint,
  productPrint,
  getLabelDetail,
  productExport,
  warehouseRevoke,
  inOutScrap,
  sequenceScrap,
  finishedScrap,
  materialSnPrint
} from '@/api/admin/barcode-record';
import { mapGetters } from 'vuex';
import printTimeInputForm from '@/components/print-time-input-form';
import { getPrintFormMixin } from '@/mixins/getPrintFormMixin';
import { getDetail } from '@/api/admin/area';
import { filterEmptyValues } from '@/util/util';
import { printSequence, printScrap } from '@/api/warehouse/accessoryPrinting';
import { getBigPackOption, getSmallPackOption } from '@/views/product/refactor/barcodeGeneration';
import { inOutReprint, inOutSourceList } from '@/api/warehouse/warehouse-label-create-print';
export default {
  name: 'AdminBarcodeRecord',
  components: {
    CommonModalTemplate,
    CommonPrintersTemplate,
    userTableConfig,
    printTimeInputForm
  },
  mixins: [getPrintFormMixin],
  data() {
    return {
      pageCode: 'ADMIN_BARCODE_RECORD',
      form: {},
      query: {},
      loading: true,
      title: '',
      detailLoading: false,
      detailModal: false,
      flagType: false,
      scrapData: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      detailData: [],
      bigSelectionList: [],
      data: [],
      option: {
        height: 'calc(100vh - 520px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 24,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        addBtn: false,
        delBtn: false,
        viewBtn: false,
        viewBtnText: '详情',
        viewTitle: '详情',
        editBtn: false,
        selection: false,
        dialogClickModal: false,
        indexLabel: '序号',
        menuWidth: 250,
        columnBtn: false,
        searchLabelWidth: 100,
        column: [
          {
            label: '大类',
            prop: 'sequenceDefinitionType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=serial',
            cascader: ['sequenceDefinitionSubType'],
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            change: ({ column, value }) => {
              this.getSubTypeData(value);
            },
            searchSpan: 6,
            search: true
          },
          {
            label: '小类',
            prop: 'sequenceDefinitionSubType',
            // dicUrl: '/api/blade-system/dict/dictionary?code={{key}}',
            // props: {
            //   label: 'dictValue',
            //   value: 'dictKey'
            // },
            formatter: (row) => {
              return subTypeMap[row.sequenceDefinitionSubType] || '';
            },
            fromslot: true,
            searchSpan: 6,
            type: 'select',
            search: true
          },
          {
            label: '包装层级类型',
            prop: 'packLevelType',
            type: 'select',
            dicData: [
              {
                label: '单层',
                value: 'SINGLE_PACK'
              },
              {
                label: '双层',
                value: 'DOUBLE_PACK'
              }
            ]
          },
          {
            label: '单据号',
            prop: 'orderNo',
            searchSpan: 6,
            search: true
          },
          {
            label: '物料编码',
            prop: 'partNo',
            searchSpan: 6,
            search: true
          },
          {
            label: '序列号规则',
            prop: 'sequenceNumberFormat'
          },

          {
            label: '起始流水号',
            prop: 'sequenceNumberFrom',
            searchSpan: 6,
            search: true
          },
          {
            label: '结束流水号',
            prop: 'sequenceNumberTo'
          },
          {
            label: '数量',
            prop: 'quantity',
            width: 130
          },
          {
            label: '操作端',
            prop: 'terminal'
          },
          {
            label: '操作类型',
            prop: 'generationType',
            type: 'select',
            search: true,
            searchSpan: 6,
            dicData: [
              { label: '生成', value: 'GENERATE' },
              { label: '报废', value: 'SCRAP' },
              { label: '增补', value: 'APPEND' },
              { label: '置换', value: 'REPLACE' },
              { label: '撤销', value: 'REVOKE' }
            ]
            // search: true
          },
          {
            label: '操作人',
            prop: 'operatorName'
          },
          {
            label: '操作时间',
            prop: 'createTime'
          },
          {
            label: '状态',
            prop: 'isPrinted',
            search: true,
            searchSpan: 6,
            type: 'select',
            dicData: [
              { value: 0, label: '未打印' },
              { value: 1, label: '已打印' }
            ]
          },
          {
            label: '备注',
            prop: 'remark'
          },
          {
            label: '原因说明',
            prop: 'reasonCode'
          },
          {
            label: '序列号',
            prop: 'sequenceNumber',
            hide: true,
            searchSpan: 6,
            search: true
          },
          {
            label: '操作时间',
            prop: 'datetimerange',
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            search: true,
            searchSpan: 12,
            hide: true
          }
        ]
      },
      detailOption: {
        addBtn: false,
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        delBtn: false,
        viewBtn: false,
        editBtn: false,
        selection: false,
        refreshBtn: false,
        menu: false,
        dialogClickModal: false,
        rowSelectionType: 'single',
        indexLabel: '序号',
        column: [
          {
            label: '产品序列号',
            prop: 'sequence',
            slot: true
          }
        ]
      },
      tableOption: {},
      printInfoModel: false,
      printInfo: {},
      printInfoOption: {
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '起始流水号',
            prop: 'startSequenceNumber',
            span: 20
          },
          {
            label: '结束流水号',
            prop: 'endSequenceNumber',
            span: 20
          },
          // {
          //   label: '重打流水号范围',
          //   prop: 'sequenceNumberFromTo',
          //   row: true,
          //   span: 20,
          //   rules: [
          //     {
          //       required: true,
          //       message: '请输入重打流水号范围',
          //       trigger: 'blur'
          //     }
          //   ]
          // },
          {
            label: '打印机',
            prop: 'equipmentName',
            span: 20,
            type: 'search',
            placeholder: '请选择 打印机',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择打印机',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPrintersModal();
            }
          },
          {
            label: '标签模版',
            prop: 'labelTemplateName',
            span: 20,
            type: 'search',
            placeholder: '请选择 标签模板',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择标签模板',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLabelTemplateModal();
            }
          }
        ]
      },
      revokeVisible: false,
      revoke: {},
      revokeOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 110,
        column: [
          {
            label: '起始流水号',
            prop: 'startSequenceNumber',
            span: 24,
            disabled: true
          },
          {
            label: '结束流水号',
            prop: 'endSequenceNumber',
            span: 24,
            disabled: true
          },
          {
            label: '原因说明',
            prop: 'reason',
            span: 24,
            type: 'textarea',
            maxlength: 50,
            showWordLimit: true,
            rules: [
              {
                required: true,
                message: '请输入原因说明',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      scrapModel: false,
      scrap: {},
      scrapOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 110,
        column: [
          {
            label: '起始流水号',
            prop: 'sequenceNumberFrom',
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入起始流水号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '结束流水号',
            prop: 'sequenceNumberTo',
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入结束流水号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '原因说明',
            prop: 'reason',
            span: 24,
            type: 'textarea',
            maxlength: 50,
            showWordLimit: true,
            rules: [
              {
                required: true,
                message: '请输入原因说明',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      timer: new Date().getTime(),
      modalName: '',
      sourceType: '',
      subTypeList: [],
      dialogTitle: '',
      smallPackOption: getSmallPackOption(this),
      bigPackOption: getBigPackOption(this),
      barcodeDialog: false,
      detailSelection: [],
      smallDialog: false,
      bigPackData: [],
      bigLoading: false,
      smallLoading: false,
      smallPackData: [],
      bigForm: {},
      smallForm: {},
      bigPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      smallPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      rowId: '',
      sourceId: ''
    };
  },
  computed: {
    ...mapGetters(['permission', 'userInfo'])
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  methods: {
    searchChange(params, done) {
      if (params.datetimerange && params.datetimerange.length > 0) {
        params.startTime = params.datetimerange[0];
        params.endTime = params.datetimerange[1];
        delete params.datetimerange;
      }
      // this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentDetailChange(currentPage) {
      this.detailPage.currentPage = currentPage;
      this.getDetailInfo();
    },
    sizeDetailChange(pageSize) {
      this.detailPage.pageSize = pageSize;
      this.getDetailInfo();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      //   this.loading = false;
      //   this.data = [{ barCodeType: '', barCodeRule: '123' }];
      this.loading = true;
      const query = this._cloneDeep(this.query);
      if (query.datetimerange && query.datetimerange.length > 0) {
        delete query.datetimerange;
      }
      getPage(page.currentPage, page.pageSize, Object.assign(params, query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        // [] || dataListTable
        this.data = this._map(data.records, (item) => {
          return {
            ...item,
            sheetNo: item.sheetNo || item.orderNo
          };
        });
        this.loading = false;
      });
    },
    async getSubTypeData(val) {
      try {
        const res = await getCategory({ code: val });
        this.subTypeList = (res.data.data || []).map((item) => ({
          label: item.dictValue,
          value: item.dictKey
        }));
      } catch (e) {
        console.warn(e);
      }
    },
    async getDefaultPrinter(partNo) {
      // const { user_id } = this.userInfo;
      try {
        const res = await getPrinterNew({ partNo });
        return res.data.data || {};
      } catch (e) {
        console.warn(e);
      }
    },
    closeDetailModel() {
      this.detailModal = false;
      this.detailData = [];
      this.detailPage = {
        pageSize: 20,
        currentPage: 1,
        total: 0
      };
    },
    async rowView(row) {
      if (row.packLevelType && row.packLevelType === 'DOUBLE_PACK') {
        this.dialogTitle = '详情';
        this.rowId = row.id;
        this.sourceId = row.sourceId;
        await this.getBigDetail();
        this.barcodeDialog = true;
      } else {
        this.form = row;
        this.detailModal = true;
        this.getDetailInfo();
      }
    },
    async handleViewSmallPack(row) {
      this.parentId = row.id;
      await this.getSmallDetail();
      this.smallDialog = true;
    },
    async getSmallDetail() {
      try {
        const params = {
          receivingId: this.sourceId,
          parentId: this.parentId,
          current: this.smallPage.currentPage,
          size: this.smallPage.pageSize
        };
        const res = await inOutSourceList(params);
        const data = res.data.data;
        this.smallPage.total = data.total;
        this.smallPackData = data.records;
      } catch (e) {
        console.log(e);
      }
    },
    async getBigDetail() {
      try {
        const params = {
          sequenceGenerationId: this.rowId,
          receivingId: this.sourceId,
          parentId: -1,
          current: this.bigPage.currentPage,
          size: this.bigPage.pageSize
        };
        this.bigLoading = true;
        const res = await inOutSourceList(params);
        const data = res.data.data;
        this.bigPage.total = data.total;
        this.bigPackData = data.records;
      } catch (e) {
        console.log(e);
      } finally {
        this.bigLoading = false;
      }
    },
    getDetailInfo() {
      this.detailLoading = true;
      getLabelDetail(this.detailPage.currentPage, this.detailPage.pageSize, { id: this.form.id }).then((res) => {
        const data = res.data.data;
        this.detailData = data.records;
        this.detailPage.total = data.total;
        this.detailLoading = false;
      });
    },
    async rowPrint(row) {
      let startColumn = this.findObject(this.printInfoOption.column, 'startSequenceNumber');
      let endColumn = this.findObject(this.printInfoOption.column, 'endSequenceNumber');
      if (row.packLevelType && row.packLevelType === 'DOUBLE_PACK') {
        this.$set(startColumn, 'display', false);
        this.$set(endColumn, 'display', false);
        this.dialogTitle = '重打';
        this.rowId = row.id;
        this.sourceId = row.sourceId;
        await this.getBigDetail();
        this.barcodeDialog = true;
      } else {
        if (row.partNo) {
          try {
            const printer = await this.getDefaultPrinter(row.partNo);
            const { labelTemplateId = '', equipmentId = '', equipmentName = '', labelTemplateName = '' } = printer;
            this.printInfo = {
              labelTemplateId: labelTemplateId,
              labelTemplateName: labelTemplateName,
              equipmentId: equipmentId,
              equipmentName
            };
          } catch (e) {
            console.warn(e);
          }
        }
        this.printInfoModel = true;
        this.title = row.isPrinted === 0 ? '打印' : '重打';
        this.sourceType = row.sourceType;
        this.$set(this.printInfo, 'generationId', row.id);
        this.$set(this.printInfo, 'sourceId', row.sourceId);
        let startColumn = this.findObject(this.printInfoOption.column, 'startSequenceNumber');
        let endColumn = this.findObject(this.printInfoOption.column, 'endSequenceNumber');
        if (row.isPrinted === 1) {
          this.printInfo.startSequenceNumber = row.sequenceNumberFrom;
          this.printInfo.endSequenceNumber = row.sequenceNumberTo;
          this.$set(startColumn, 'display', true);
          this.$set(endColumn, 'display', true);
        } else {
          this.$set(startColumn, 'display', false);
          this.$set(endColumn, 'display', false);
        }
      }
    },
    closeScrapModel() {
      this.$refs.scrapForm.resetForm();
    },
    closeRevokeDialog() {
      this.$refs.revokeForm.resetForm();
    },
    /**
     * 报废
     */
    rowScrap(row) {
      this.scrapData = row;

      let startColumn = this.findObject(this.scrapOption.column, 'sequenceNumberFrom');
      let endColumn = this.findObject(this.scrapOption.column, 'sequenceNumberTo');
      if (row.packLevelType) {
        this.$set(startColumn, 'display', false);
        this.$set(endColumn, 'display', false);
      } else {
        this.scrap.sequenceGenerationId = row.id;
        this.scrap.sequenceNumberFrom = row.sequenceNumberFrom;
        this.scrap.sequenceNumberTo = row.sequenceNumberTo;
        this.$set(startColumn, 'display', true);
        this.$set(endColumn, 'display', true);
      }
      this.scrapModel = true;
    },
    handleRevoke(row) {
      this.revoke.sequenceDefinitionSubType = row.sequenceDefinitionSubType;
      this.revoke.sequenceGenerationId = row.id;
      this.revoke.startSequenceNumber = row.sequenceNumberFrom;
      this.revoke.endSequenceNumber = row.sequenceNumberTo;
      this.revokeVisible = true;
    },
    isShowBtn(row) {
      return (
        ['LABEL_MATERIAL_BY_RECEIVING', 'LABEL_FINISHED_BY_WO', 'LABEL_PRODUCT_BY_WO', 'SHEET_BY_SYSTEM_SEQUENCE_DEFINITION'].includes(row.sourceType) &&
        !['REVOKE', 'SCRAP'].includes(row.generationType)
      );
    },
    isShowScrapBtn(row) {
      return (
        ['WORK_IN_PROGRESS', 'RAW_MATERIAL_PACKAGING', 'FINISHED_PRODUCT_PACKAGING', 'ACCESSORIES', 'NG'].includes(row.sequenceDefinitionSubType) &&
        !['REVOKE', 'SCRAP', 'REPLACE'].includes(row.generationType)
      );
    },
    isShowRevokeBtn(row) {
      return ['RAW_MATERIAL_PACKAGING', 'ACCESSORIES'].includes(row.sequenceDefinitionSubType) && !['REVOKE', 'SCRAP'].includes(row.generationType);
    },
    /**
     * 置换
     */
    rowSubstitution(row) {
      this.substitutionModel = true;
      this.sourceType = row.type;
      this.$set(this.substitution, 'sequenceGenerationId', row.id);
      this.$set(this.substitution, 'startSequenceNumber', row.sequenceNumberFrom);
      this.$set(this.substitution, 'endSequenceNumber', row.sequenceNumberTo);
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 获取打印机
     */
    openPrintersModal() {
      this.modalName = 'printersModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择打印机（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '打印机编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 110
          },
          {
            label: '打印机名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 110
          }
        ]
      };
    },
    /**
     * 打开标签模板模态框
     */
    openLabelTemplateModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模版（双击进行选择）',
        url: '/api/mes-admin/labeltemplate/page?status=1',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '标签名称',
            prop: 'name',
            search: true
          },
          {
            label: '标签代码',
            prop: 'code',
            search: true
          },
          {
            label: '版本名称',
            prop: 'revision'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl'
          },
          {
            label: '打印标签',
            prop: 'fileUrl'
          }
        ]
      };
    },
    /**
     * 获取选中打印机标签模版信息
     */
    getSelectedRows(rowData) {
      if (this.modalName === 'printersModal') {
        if (this.printInfoModel) {
          this.$set(this.printInfo, 'equipmentId', rowData.id);
          this.$set(this.printInfo, 'equipmentName', rowData.name);
        } else {
          this.$set(this.substitution, 'equipmentId', rowData.id);
          this.$set(this.substitution, 'equipmentName', rowData.name);
        }
      } else if (this.modalName === 'labelTemplateModal') {
        if (this.printInfoModel) {
          this.$set(this.printInfo, 'labelTemplateId', rowData.id);
          this.$set(this.printInfo, 'labelTemplateName', rowData.name);
          const dataId = rowData.dataId;
          if (dataId) {
            this.getDetail(dataId);
          }
        } else {
          this.$set(this.substitution, 'labelTemplateId', rowData.id);
          this.$set(this.substitution, 'labelTemplateName', rowData.fileName);
        }
      }
    },
    /**
     * 打印
     */
    async printSubmit() {
      this.$refs.printForm.validate(async (valid, done) => {
        if (valid) {
          if (this.title === '重打') {
            this.printInfo.fromSequenceNumber = this._cloneDeep(this.printInfo.startSequenceNumber);
            this.printInfo.toSequenceNumber = this._cloneDeep(this.printInfo.endSequenceNumber);
          } else {
            delete this.printInfo.startSequenceNumber;
            delete this.printInfo.endSequenceNumber;
            delete this.printInfo.fromSequenceNumber;
            delete this.printInfo.toSequenceNumber;
          }
          let res;
          try {
            let inOutParams = {
              equipmentId: this.printInfo.equipmentId, //   打印机id
              labelMaterialIdSet: this.printInfo.id,
              labelTemplateId: this.printInfo.labelTemplateId //   标签
            };
            if (this.dialogTitle === '重打') {
              res = await inOutReprint(inOutParams);
            } else if (['LABEL_MATERIAL_BY_RECEIVING'].includes(this.sourceType)) {
              if (this.title === '打印') {
                let params = {
                  equipmentId: this.printInfo.equipmentId,
                  labelTemplateId: this.printInfo.labelTemplateId,
                  sequenceGenerationId: this.printInfo.generationId,
                  workOrderId: this.printInfo.sourceId
                };
                res = await materialSnPrint(params);
              } else {
                let params = {
                  sequenceNumberFrom: this.printInfo.fromSequenceNumber,
                  sequenceNumberTo: this.printInfo.toSequenceNumber,
                  equipmentId: this.printInfo.equipmentId,
                  labelTemplateId: this.printInfo.labelTemplateId,
                  generationId: this.printInfo.generationId,
                  workOrderId: this.printInfo.sourceId
                };
                res = await productPrint(params);
              }
            } else if (['LABEL_FINISHED_BY_WO'].includes(this.sourceType)) {
              if (this.title === '打印') {
                let params = {
                  equipmentId: this.printInfo.equipmentId,
                  labelTemplateId: this.printInfo.labelTemplateId,
                  sequenceGenerationId: this.printInfo.generationId,
                  workOrderId: this.printInfo.sourceId
                };
                res = await finishSnPrint(params);
              } else {
                let params = {
                  startSequenceNumber: this.printInfo.fromSequenceNumber,
                  endSequenceNumber: this.printInfo.toSequenceNumber,
                  equipmentId: this.printInfo.equipmentId,
                  labelTemplateId: this.printInfo.labelTemplateId,
                  generationId: this.printInfo.generationId,
                  workOrderId: this.printInfo.sourceId
                };
                res = await warehouseSnPrint(params);
              }
            } else if (['LABEL_PRODUCT_BY_WO'].includes(this.sourceType)) {
              if (this.title === '打印') {
                let params = {
                  equipmentId: this.printInfo.equipmentId,
                  labelTemplateId: this.printInfo.labelTemplateId,
                  sequenceGenerationId: this.printInfo.generationId,
                  workOrderId: this.printInfo.sourceId
                };
                res = await productSnPrint(params);
              } else {
                let params = {
                  fromSequenceNumber: this.printInfo.fromSequenceNumber,
                  toSequenceNumber: this.printInfo.toSequenceNumber,
                  equipmentId: this.printInfo.equipmentId,
                  labelTemplateId: this.printInfo.labelTemplateId,
                  sequenceGenerationId: this.printInfo.generationId,
                  workOrderId: this.printInfo.sourceId
                };
                res = await productSnRePrint(params);
              }
            } else if (['SHEET_BY_SYSTEM_SEQUENCE_DEFINITION'].includes(this.sourceType)) {
              if (this.title === '打印') {
                let params = {
                  equipmentId: this.printInfo.equipmentId,
                  labelTemplateId: this.printInfo.labelTemplateId,
                  sequenceGenerationId: this.printInfo.generationId,
                  workOrderId: this.printInfo.sourceId
                };
                res = await malfunctionSnPrint(params);
              } else {
                let params = {
                  fromSequenceNumber: this.printInfo.fromSequenceNumber,
                  toSequenceNumber: this.printInfo.toSequenceNumber,
                  equipmentId: this.printInfo.equipmentId,
                  labelTemplateId: this.printInfo.labelTemplateId,
                  sequenceGenerationId: this.printInfo.generationId,
                  workOrderId: this.printInfo.sourceId
                };
                res = await malfunctionSnRePrint(params);
              }
            }
            this.printInfoModel = false;
            this.$refs.printForm.resetFields();
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            this.onLoad(this.page);
            done();
          } catch (e) {
            console.warn('e', e);
            done();
          }
        }
      });
    },
    async handlePrintSequence(otherInfo) {
      delete this.printInfo.startSequenceNumber;
      delete this.printInfo.endSequenceNumber;
      delete this.printInfo.fromSequenceNumber;
      delete this.printInfo.toSequenceNumber;
      delete this.printInfo.equipmentName;
      delete this.printInfo.labelTemplateName;
      const params = {
        ...this.printInfo
      };
      if (Object.keys(otherInfo).length > 0) {
        params.printInput = JSON.stringify(otherInfo);
      }
      let res;
      try {
        if (['RAW_MATERIAL_PACKAGING', 'FINISHED_PRODUCT_PACKAGING'].includes(this.printInfo.sequenceDefinitionSubType)) {
          res = await warehousePrint(params);
        } else if (['ACCESSORIES'].includes(this.printInfo.sequenceDefinitionSubType)) {
          res = await printSequence(obj);
        } else {
          res = await productPrint(params);
        }
        this.printInfoModel = false;
        this.$refs.printForm.resetFields();
        this.$message({
          type: 'success',
          message: res.data.msg
        });
        this.onLoad(this.page);
      } catch (e) {
        console.warn(e);
      }
    },
    beforeOpen(done, type) {
      if (type === 'view') {
        this.form.sequenceDefinitionSubType = subTypeMap[this.form.sequenceDefinitionSubType];
      }
      done();
    },
    async handleExport() {
      const params = this._cloneDeep(this.query);
      if (!this.query.datetimerange || !this.query.datetimerange.length) {
        this.$message.warning('导出数据的操作时间范围不能为空');
        return;
      }
      if (this.query.datetimerange && this.query.datetimerange.length > 0) {
        const startTime = this.$moment(this.query.datetimerange[0]);
        const endTime = this.$moment(this.query.datetimerange[1]);
        const diffInDays = endTime.diff(startTime, 'days');
        if (diffInDays > 31) {
          this.$message.warning('导出数据的操作时间范围不能超过31天');
          return;
        }
        params.startTime = params.datetimerange[0];
        params.endTime = params.datetimerange[1];
        delete params.datetimerange;
      }
      const loading = this.$loading({
        lock: true,
        text: '数据导出中请稍等。',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      try {
        const res = await productExport(filterEmptyValues(params));
        const blob = new Blob([res.data]);
        const fileName = '标签记录导出.xlsx';
        const link = document.createElement('a');
        link.download = fileName;
        link.style.display = 'none';
        link.href = URL.createObjectURL(blob);
        document.body.append(link);
        link.click();
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      } catch (e) {
        const failMsg = await this.blobToJson(e.data);
        this.$message.error(failMsg.msg);
      } finally {
        loading.close();
      }
    },
    async blobToJson(blob) {
      return new Promise((resolve, reject) => {
        blob.arrayBuffer().then(
          async (arrayBuffer) => {
            resolve(JSON.parse(Buffer.from(arrayBuffer).toString('utf-8')));
          },
          (error) => {
            reject(error);
          }
        );
      });
    },
    /**
     * 撤销
     */
    revokeSubmit() {
      this.$refs.revokeForm.validate(async (valid, done) => {
        if (valid) {
          let res;
          try {
            const params = {
              sequenceGenerationId: this.revoke.sequenceGenerationId,
              reason: this.revoke.reason
            };
            // const res = await warehouseRevoke(params);
            if (['ACCESSORIES'].includes(this.printInfo.sequenceDefinitionSubType)) {
              res = await printScrap(params);
            } else {
              res = await warehouseRevoke(params);
            }
            this.$refs.revokeForm.resetFields();
            this.revokeVisible = false;
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            this.onLoad(this.page);
          } catch (e) {
            console.warn(e);
          } finally {
            done();
          }
        }
      });
    },
    /**
     * 作废
     */
    scrapSubmit() {
      if (this.scrapData.type === 'MATERIAL' && this.scrapData.status !== 1) {
        this.$message.error('该条记录中关联的包装条码已使用，不允许作废！');
        return;
      }
      this.$refs.scrapForm.validate(async (valid, done) => {
        if (valid) {
          let res;
          try {
            if (this.scrapData.packLevelType) {
              await this.$confirm('报废后，所有的小包条码、大包条码都会报废，是否确认报废条码', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(async () => {
                const data = {
                  sequenceGenerationId: this.scrapData.id,
                  reason: this.scrap.reason
                };
                res = await inOutScrap(data);
              });
            } else if (['RAW_MATERIAL_PACKAGING'].includes(this.scrapData.sequenceDefinitionSubType)) {
              res = await warehouseScrap(this.scrap);
            } else if (['FINISHED_PRODUCT_PACKAGING'].includes(this.scrapData.sequenceDefinitionSubType)) {
              res = await finishedScrap(this.scrap);
            } else if (['ACCESSORIES'].includes(this.printInfo.sequenceDefinitionSubType)) {
              const params = {
                sequenceGenerationId: this.revoke.sequenceGenerationId,
                reason: this.revoke.reason
              };
              res = await printScrap(params);
            } else {
              res = await sequenceScrap(this.scrap);
            }
            this.$refs.scrapForm.resetFields();
            this.scrapModel = false;
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            this.onLoad(this.page);
          } catch (e) {
            // console.warn(e);
          } finally {
            done();
          }
          // (this.scrapData.type === 'MATERIAL' ? matrialSequenceScrap(this.scrap) : sequenceScrap(this.scrap)).then(
          //   (res) => {
          //     this.$refs.scrapForm.resetFields();
          //     this.scrapModel = false;
          //     this.$message({
          //       type: 'success',
          //       message: res.data.msg
          //     });
          //     this.onLoad(this.page);
          //     done();
          //   },
          //   (error) => {
          //     done();
          //   }
          // );
        }
      });
    },
    bigSizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getBigDetail();
    },
    bigCurrentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.getBigDetail();
    },
    bigSelectionChange(list) {
      this.bigSelectionList = list;
    },
    detailSizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getBigDetail();
    },
    detailCurrentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.getBigDetail();
    },
    detailSelectionChange(list) {
      this.detailSelection = list;
    },
    handleMultiBigPackReprint() {
      const printList = this.bigSelectionList.filter((item) => item.status === 1);
      if (printList.length > 0) {
        const nameStr = printList.map((item) => item.sequenceNumber).join(',');
        this.$message.warning(`包装条码${nameStr}状态为未打印，请先在【打印操作】打印！`);
        return;
      }
      this.printInfo.id = this.bigSelectionList.map((item) => item.id);
      this.printInfoModel = true;
      this.title = '重打';
    },
    handleMultiSmallPackReprint() {
      const printList = this.detailSelection.filter((item) => item.status === 1);
      if (printList.length > 0) {
        const nameStr = printList.map((item) => item.sequenceNumber).join(',');
        this.$message.warning(`包装条码${nameStr}状态为未打印，请先在【打印操作】打印！`);
        return;
      }
      this.printInfo.id = this.detailSelection.map((item) => item.id);
      this.printInfoModel = true;
      this.title = '重打';
    },
    handleReprint(row) {
      this.printInfo.id = [row.id];
      this.printInfoModel = true;
      this.title = '重打';
    }
  }
};
</script>

<style scoped lang="scss">
.menu-option {
  text-align: left;
  padding: 0 30px;
}
.sequenceNumber {
  position: relative;
  padding: 8px 0 8px 0;
}
.detail {
  ::v-deep .el-table--small td {
    padding: 0;
  }
  ::v-deep .el-table .cell {
    padding: 0 0 0 8px;
  }
}
</style>
